package com.database.objects;

import java.io.ByteArrayOutputStream;

import javax.persistence.*;

import org.tmatesoft.svn.core.io.SVNRepository;

import com.load.exception.*;
import com.load.utils.FileUtil;

@Entity
@Table(name = "file")
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class File extends Element<Commit, Class> {

	private static final long serialVersionUID = -2812389908106888576L;

	@Id
	@Column(name = "fil_id", nullable = false, unique = true)
	@GeneratedValue(generator = "seq", strategy = GenerationType.SEQUENCE)
	@SequenceGenerator(name = "seq", sequenceName = "seq_file", allocationSize = 1, initialValue = 1)
	protected Integer id;

	@Column(name = "fil_path", nullable = false)
	protected String path;

	@Column(name = "fil_is_file", nullable = false)
	protected boolean file;

	@Enumerated(EnumType.STRING)
	@Column(name = "fil_status", nullable = false)
	protected Status status;

	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "com_id", nullable = false)
	protected Commit commit;

	@Transient
	protected ByteArrayOutputStream baos;

	public Integer getId() {
		return id;
	}

	public String getPath() {
		return path;
	}

	public String getPathWithVersionRepository() {
		return getUrlVersionRepository() + "" + path;
	}

	public boolean isFile() {
		return file;
	}

	public void setFile(boolean file) {
		this.file = file;
	}

	@Override
	public Status getStatus() {
		return status;
	}

	@Override
	public void setStatus(Status status) {
		this.status = status;
	}

	public ByteArrayOutputStream getBaos() {
		return baos;
	}

	public void setBaos(SVNRepository svnRepository) {
		try {
			baos = FileUtil.obtainContent(svnRepository, this);
			file = baos != null;
		} catch (DelFileException e) {
			file = true;
		} catch (DirectoryException e) {
			file = false;
		}
	}

	public void setBaos(ByteArrayOutputStream baos) {
		this.baos = baos;
	}

	@Override
	public Commit getParent() {
		return commit;
	}

	@Override
	public void setParent(Element<?, ?> parent) {
		commit = (Commit) parent;
	}

	public Long getNumberCommit() {
		return commit.getNumber();
	}

	@Override
	public String getLabel() {
		return path;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + (id == null ? 0 : id.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (getClass() != obj.getClass()) {
			return false;
		}
		FileOO other = (FileOO) obj;
		if (id == null) {
			if (other.id != null) {
				return false;
			}
		} else if (!id.equals(other.id)) {
			return false;
		}
		return true;
	}

	@Override
	public String toString() {
		return id + " " + path;
	}

	public abstract boolean isFileOO();
	
}